var express = require("express");
var router = express.Router();
let { GoodsModel, ClassifysModel, AdvertisementModel } = require("../db/index");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, "../upload/products");
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, "product-" + uniqueSuffix + path.extname(file.originalname));
  },
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只允许上传图片
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("只允许上传图片文件"), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制5MB
  },
});

/* GET home page. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});

// 图片上传接口
router.post(
  "/uploadimage",
  upload.single("image"),
  async function (req, res, next) {
    try {
      if (!req.file) {
        return res.status(400).send({
          code: 400,
          msg: "请选择要上传的图片",
        });
      }

      // 返回图片URL
      const imageUrl = `/upload/products/${req.file.filename}`;

      res.send({
        code: 200,
        msg: "图片上传成功",
        data: {
          url: imageUrl,
          filename: req.file.filename,
        },
      });
    } catch (error) {
      console.error("图片上传失败:", error);
      res.status(500).send({
        code: 500,
        msg: "图片上传失败",
        error: error.message,
      });
    }
  }
);

// =======商品接口======

// 获取商品分类
router.get("/getClassifys", async function (req, res, next) {
  // 查询所有分类
  let ggb = await ClassifysModel.find();
  res.send({
    code: 200,
    msg: "获取成功",
    data: ggb,
  });
});

// 获取商品数据
router.get("/getproducts", async function (req, res, next) {
  const { category, page = 1, limit = 10, keyword } = req.query;
  let query = {};

  // 如果有分类，就查询对应分类的商品
  if (category) {
    query.category = category;
  }

  // 如果有关键词，就模糊搜索
  if (keyword) {
    query.$or = [
      { title: { $regex: keyword, $options: "i" } },
      { description: { $regex: keyword, $options: "i" } },
    ];
  }

  try {
    const skip = (page - 1) * limit;
    const goods = await GoodsModel.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    const total = await GoodsModel.countDocuments(query);

    res.send({
      code: 200,
      msg: "获取成功",
      data: {
        list: goods,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取商品失败",
      error: error.message,
    });
  }
});

// 获取商品详情
router.get("/getproduct/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const product = await GoodsModel.findOne({ id });

    if (!product) {
      return res.status(404).send({
        code: 404,
        msg: "商品不存在",
      });
    }

    res.send({
      code: 200,
      msg: "获取成功",
      data: product,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取商品详情失败",
      error: error.message,
    });
  }
});

// 获取商品分类
// 获取商品数据
router.get("/productscategory", async function (req, res, next) {
  const { category } = req.query;
  let query = {};

  // 如果有分类，就查询对应分类的商品
  if (category) {
    query.category = category;
  }

  try {
    const goods = await GoodsModel.find(query).sort({ createdAt: -1 });

    res.send({
      code: 200,
      msg: "获取成功",
      data: goods,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取商品失败",
      error: error.message,
    });
  }
});

// 获取热门商品
router.get("/gethotproducts", async function (req, res, next) {
  try {
    // 热门在activity这个数组的里边
    // activity是["拼团","热门"]这样的
    const hotProducts = await GoodsModel.find({
      activity: { $in: ["热门"] },
      status: { $ne: "deleted" },
    })
      .sort({ sales: -1 })
      .limit(10);

    res.send({
      code: 200,
      msg: "获取成功",
      data: hotProducts,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取热门商品失败",
      error: error.message,
    });
  }
});

// 获取推荐商品
router.get("/getrecommendproducts", async function (req, res, next) {
  try {
    const recommendProducts = await GoodsModel.find({
      activity: { $in: ["推荐"] },
      status: { $ne: "deleted" },
    })
      .sort({ createdAt: -1 })
      .limit(10);

    res.send({
      code: 200,
      msg: "获取成功",
      data: recommendProducts,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取推荐商品失败",
      error: error.message,
    });
  }
});

// 获取限时秒杀商品
router.get("/getseckillproducts", async function (req, res, next) {
  try {
    const seckillProducts = await GoodsModel.find({
      activity: { $in: ["限时秒杀"] },
    }).sort({ createdAt: -1 });

    res.send({
      code: 200,
      msg: "获取成功",
      data: seckillProducts,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取秒杀商品失败",
      error: error.message,
    });
  }
});

// 获取拼团商品
router.get("/getgroupproducts", async function (req, res, next) {
  try {
    const groupProducts = await GoodsModel.find({
      activity: { $in: ["特惠拼团"] },
    }).sort({ createdAt: -1 });

    res.send({
      code: 200,
      msg: "获取成功",
      data: groupProducts,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "获取拼团商品失败",
      error: error.message,
    });
  }
});

// 添加商品
router.post("/addproduct", async function (req, res, next) {
  try {
    const productData = req.body;

    // 生成商品ID
    const timestamp = Date.now();
    const randomNum = Math.floor(Math.random() * 1000);
    productData.id = `g${timestamp}${randomNum}`;

    // 确保数组字段有默认值
    if (!productData.tags) productData.tags = [];
    if (!productData.activity) productData.activity = [];

    // 设置默认状态为启用
    if (!productData.status) productData.status = "active";

    // 验证状态值
    if (
      productData.status &&
      !["active", "inactive", "deleted"].includes(productData.status)
    ) {
      return res.status(400).send({
        code: 400,
        msg: "状态值无效，只能是 active、inactive 或 deleted",
      });
    }

    const newProduct = new GoodsModel(productData);
    await newProduct.save();

    res.send({
      code: 200,
      msg: "添加商品成功",
      data: newProduct,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "添加商品失败",
      error: error.message,
    });
  }
});

// 更新商品
router.put("/updateproduct/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 确保数组字段有默认值
    if (updateData.tags === undefined) updateData.tags = [];
    if (updateData.activity === undefined) updateData.activity = [];

    // 验证状态值
    if (
      updateData.status &&
      !["active", "inactive", "deleted"].includes(updateData.status)
    ) {
      return res.status(400).send({
        code: 400,
        msg: "状态值无效，只能是 active、inactive 或 deleted",
      });
    }

    const updatedProduct = await GoodsModel.findOneAndUpdate(
      { id },
      updateData,
      { new: true }
    );

    if (!updatedProduct) {
      return res.status(404).send({
        code: 404,
        msg: "商品不存在",
      });
    }

    res.send({
      code: 200,
      msg: "更新商品成功",
      data: updatedProduct,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "更新商品失败",
      error: error.message,
    });
  }
});

// 更新商品状态
router.patch("/updatestatus/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const { status } = req.body;

    const updatedProduct = await GoodsModel.findOneAndUpdate(
      { id },
      { status },
      { new: true }
    );

    if (!updatedProduct) {
      return res.status(404).send({
        code: 404,
        msg: "商品不存在",
      });
    }

    res.send({
      code: 200,
      msg: "更新商品状态成功",
      data: updatedProduct,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "更新商品状态失败",
      error: error.message,
    });
  }
});

// 删除商品
router.delete("/deleteproduct/:id", async function (req, res, next) {
  try {
    const { id } = req.params;

    const deletedProduct = await GoodsModel.findOneAndDelete({ id });

    if (!deletedProduct) {
      return res.status(404).send({
        code: 404,
        msg: "商品不存在",
      });
    }

    res.send({
      code: 200,
      msg: "删除商品成功",
      data: deletedProduct,
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "删除商品失败",
      error: error.message,
    });
  }
});

// 获取广告
router.get("/getlunbo", async function (req, res, next) {
  // 查询所有分类
  let ggb = await AdvertisementModel.find();
  res.send({
    code: 200,
    msg: "获取成功",
    data: ggb,
  });
});

// 新增广告
router.post("/ad", async function (req, res, next) {
  try {
    const data = req.body;
    // 生成唯一id
    data.id = data.id || "ad" + Date.now();
    data.createdAt = new Date();
    data.updatedAt = new Date();
    const ad = new AdvertisementModel(data);
    await ad.save();
    res.send({ code: 200, msg: "新增成功", data: ad });
  } catch (e) {
    res.status(500).send({ code: 500, msg: "新增失败", error: e.message });
  }
});

// 编辑广告
router.put("/ad/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const update = req.body;
    update.updatedAt = new Date();
    const ad = await AdvertisementModel.findOneAndUpdate({ id }, update, {
      new: true,
    });
    if (!ad) return res.status(404).send({ code: 404, msg: "广告不存在" });
    res.send({ code: 200, msg: "编辑成功", data: ad });
  } catch (e) {
    res.status(500).send({ code: 500, msg: "编辑失败", error: e.message });
  }
});

// 删除广告
router.delete("/ad/:id", async function (req, res, next) {
  try {
    const { id } = req.params;
    const ad = await AdvertisementModel.findOneAndDelete({ id });
    if (!ad) return res.status(404).send({ code: 404, msg: "广告不存在" });
    res.send({ code: 200, msg: "删除成功", data: ad });
  } catch (e) {
    res.status(500).send({ code: 500, msg: "删除失败", error: e.message });
  }
});

// 修改广告状态（如下线）
router.patch("/ad/:id/status", async function (req, res, next) {
  try {
    const { id } = req.params;
    const { status } = req.body;
    const ad = await AdvertisementModel.findOneAndUpdate(
      { id },
      { status, updatedAt: new Date() },
      { new: true }
    );
    if (!ad) return res.status(404).send({ code: 404, msg: "广告不存在" });
    res.send({ code: 200, msg: "状态更新成功", data: ad });
  } catch (e) {
    res.status(500).send({ code: 500, msg: "状态更新失败", error: e.message });
  }
});

module.exports = router;
